/*
 * @Author: shengduiliang 1107722390@qq.com
 * @Date: 2024-05-04 13:55:37
 * @LastEditors: shengduiliang 1107722390@qq.com
 * @LastEditTime: 2024-05-04 15:22:04
 * @FilePath: /treasure/src/network/http.ts
 * @Description: 网络请求
 */
import { cookie } from '@/utils'
import Taro from '@tarojs/taro'
import to from 'await-to-js'

export interface RequestOption {
  hideLoading?: boolean
  loadingText?: string
}

interface Response {
  data: any
  code: number
  message: string
}

const request = async (config: Taro.request.Option, { hideLoading, loadingText }: RequestOption = {}): Promise<any> => {
  if (!hideLoading) {
    Taro.showLoading({
      title: loadingText || '加载中...'
    })
  }

  const [err, res] = await to(Taro.request({
    ...config,
    header: {
      'content-type': 'application/json',
      cookie: cookie.get()
    },
    url: `${process.env.TARO_APP_BASE_URL}${config.url}`
  }))

  if (!hideLoading) {
    Taro.hideLoading()
  }
  if (err) return Promise.reject(err)
  if (res.statusCode !== 200 && res.data.status !== 200) return Promise.reject(res)
  return res.data.data
}

const post = async (config: Taro.request.Option, options?: RequestOption): Promise<any> => {
  return request(
    {
      ...config,
      method: 'POST'
    }, 
    options
  )
}

const get = async (config: Taro.request.Option, options?: RequestOption): Promise<any> => {
  return request(
    {
      ...config,
      method: 'GET'
    }, 
    options
  )
}

export default {
  request,
  post,
  get
}

